package com.core.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Aspect
@Component
public class WebLogAspect {

    private static final Logger logger = LoggerFactory.getLogger(WebLogAspect.class);

    // 切入点：匹配Controller层所有方法
    // 两个..代表所有子目录，最后括号里的两个..代表所有参数
    @Pointcut("execution(* com..controller.*.*(..))")
    public void logPointCut() {
    }

    /**
     * 前置通知：记录请求基本信息
     */
    @Before("logPointCut()")
    public void doBefore(JoinPoint joinPoint) {
        // 获取当前请求上下文（非空判断，避免NullPointException）
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            logger.warn("当前线程无HTTP请求上下文，无法记录请求信息");
            return;
        }
        HttpServletRequest request = attributes.getRequest();

        // 记录请求信息（优化日志格式，使用占位符）
        logger.info("【请求开始】");
        logger.info("请求地址: {}", request.getRequestURL().toString());
        logger.info("请求方法: {}", request.getMethod());
        logger.info("客户端IP: {}", getClientIp(request)); // 补充IP获取方法
        logger.info("调用方法: {}.{}",
                joinPoint.getSignature().getDeclaringTypeName(),
                joinPoint.getSignature().getName());
        logger.info("请求参数: {}", Arrays.toString(joinPoint.getArgs()));
        // 注意：若参数包含敏感信息（如密码），需在此处过滤（例如替换为***）
    }

    /**
     * 后置返回通知：记录响应结果
     */
    @AfterReturning(returning = "ret", pointcut = "logPointCut()")
    public void doAfterReturning(Object ret) {
        // 避免大对象打印导致日志冗余（可根据实际情况判断是否打印）
        if (ret != null) {
            String retStr = ret.toString();
            // 若返回值过长，截断显示（例如超过500字符）
            if (retStr.length() > 500) {
                retStr = retStr.substring(0, 500) + "...[省略部分内容]";
            }
            logger.info("【响应结果】: {}", retStr);
        } else {
            logger.info("【响应结果】: null");
        }
    }

    /**
     * 环绕通知：记录接口耗时
     */
    @Around("logPointCut()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        long startTime = System.currentTimeMillis();

        // 执行目标方法
        Object result = pjp.proceed();

        // 计算耗时（获取当前请求的URL，确保线程安全）
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String requestUrl = "未知URL";
        if (attributes != null && attributes.getRequest() != null) {
            requestUrl = attributes.getRequest().getRequestURL().toString();
        }
        logger.info("【请求结束】{} 接口耗时: {}ms", requestUrl, (System.currentTimeMillis() - startTime));

        return result;
    }

    /**
     * 获取客户端真实IP（处理代理场景）
     */
    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 多级代理时，取第一个非unknown的IP
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0].trim();
        }
        return ip;
    }
}
